package org.jeecg.modules.demo3.fly.service.impl;


import cn.hutool.core.util.StrUtil;
import lombok.SneakyThrows;
import org.jeecg.modules.demo3.fly.entity.*;
import org.jeecg.modules.demo3.fly.entity.assist.AxhkLandManagements;
import org.jeecg.modules.demo3.fly.entity.assist.BLatitude;
import org.jeecg.modules.demo3.fly.entity.assist.OLatitude;
import org.jeecg.modules.demo3.fly.entity.AxhkLandManagement;
import org.jeecg.modules.demo3.fly.entity.assist.WorkFinish;
import org.jeecg.modules.demo3.fly.entity.assist.qun.AxhkWorkManagements;
import org.jeecg.modules.demo3.fly.mapper.AxhkLandManagementMapper;
import org.jeecg.modules.demo3.fly.mapper.AxhkWorkManagementMapper;
import org.jeecg.modules.demo3.fly.service.IAxhkWorkManagementService;
import org.jeecg.modules.demo3.fly.utils.Scope;
import org.jeecg.modules.demo3.fly.utils.UuId;
import org.jeecg.modules.demo3.peijian.utill.DeleteFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.bind.annotation.RequestBody;

import javax.swing.plaf.synth.SynthOptionPaneUI;
import java.io.*;
import java.util.*;

/**
 * @Description: 作业管理
 * @Author: jeecg-boot
 * @Date:   2021-01-28
 * @Version: V1.0
 */
@Service
public class AxhkWorkManagementServiceImpl extends ServiceImpl<AxhkWorkManagementMapper, AxhkWorkManagement> implements IAxhkWorkManagementService {

    @Autowired
    private AxhkWorkManagementMapper axhkWorkManagementMapper;
    @Autowired
    private AxhkLandManagementMapper axhkLandManagementMapper;
    //添加地块管理-wjn
    @Override
    @SneakyThrows
    public String addLands(@RequestBody AxhkLandManagement axhkLandManagement) {
        String massifNames = axhkLandManagement.getMassifName(); //地块名称
        String massifMasterNames = axhkLandManagement.getMassifMasterName(); // 地块联系人
        String massifMasterTelephones= axhkLandManagement.getMassifMasterTelephone(); // 联系人电话号码
        String landArea = axhkLandManagement.getLandArea(); // 地块面积
        String fluckId = axhkLandManagement.getFluckId();
        String massifName = null; // 如有空格 去掉空格后的 地块名称
        boolean a = StrUtil.containsBlank(massifNames); //判断传输的地块名称是否有空格出现 如果有 删除空格
        if(a == true){
            massifName = massifNames.trim();
        }else {
            massifName = massifNames;
        }
        int num = 0;
        //这块不可写死
        String filePath = "C:\\OS\\fly\\axhk\\";
        String id = UuId.getUUID();
        String fileName = id+"axhk.txt";
        String landManagement = filePath+fileName;
        //进行强转
        //创建坐标集合装坐标
        List<BLatitude> bLatitudes = axhkLandManagement.getBoundaryList();
        List<OLatitude> oLatitudes = axhkLandManagement.getObstacleList();
        ArrayList<String> ls = new ArrayList<>();
        for(int i = 0;i<bLatitudes.size();i++){
            String myLatLng = "Blat="+String.valueOf(bLatitudes.get(i).getLat())+",Blng="+String.valueOf(bLatitudes.get(i).getLng())+"\n";
            ls.add(myLatLng);
        }
        if(oLatitudes!=null) {
            for (int i = 0; i < oLatitudes.size(); i++) {
                String myLatLng = "Olat=" + String.valueOf(oLatitudes.get(i).getLat()) + ",Olng=" + String.valueOf(oLatitudes.get(i).getLng()) + "\n";
                ls.add(myLatLng);
            }
        }
        //判断 APP用户发送过来的 地块名称是否存在
        String landName = axhkLandManagementMapper.getLandName(massifMasterTelephones,massifName);// 根据电话号码查看该用户下是否有此地块名称
        if(null == landName || !landName.equals(massifName)){ //判断 地块名称是否已经存在
            AxhkLandManagements axhkLandManagements = new AxhkLandManagements(id,massifName,massifMasterNames,massifMasterTelephones,landManagement,landArea,fluckId);
            //判断手机APP传输的 地块信息中  地块名称是否是 纯数字组成
            String massName = axhkLandManagements.getMassifName();
            boolean ent = UuId.isInteger(massName); //调用方法
            if(ent == true){ // 为true是 完全由数字类型的 字符串
                num = 0;
            }else{ // 为false 不是完全的数字类型 组成的字符串
                File file = new File(filePath,fileName);
                //判断文件是否存在
                if(!file.exists() && !file.isDirectory()){
                    file.getParentFile().mkdirs();
                    file.createNewFile();
                }
                OutputStream fos = new FileOutputStream(file);
                OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8");
                for(String bb : ls){
                    osw.write(bb);
                    osw.flush();
                }
                osw.close();
                num = axhkLandManagementMapper.insetLand(axhkLandManagements);
            }
        }else{
            num = 0;
        }
        if(num <= 0){
            return null;
        }else{
            return id;
        }
    }

    //通过群id查询该群下 所有地块信息返还给APP
    @Override
    public ArrayList<AxhkLandManagement> getByWorkId(String fluckId) {
        List<AxhkLandManagements> axhkLandManagements = axhkWorkManagementMapper.getByWorkId(fluckId);
        ArrayList<AxhkLandManagement> axhkLandManagements1 = new ArrayList<>();
        ArrayList<BLatitude> bLatitudes = null;
        ArrayList<OLatitude> oLatitudes = null;
        for(AxhkLandManagements land : axhkLandManagements){
            AxhkLandManagement axhkLandManagement = new AxhkLandManagement();
            String massifNames = land.getMassifName();
            String massifMasterNames = land.getMassifMasterName();
            String massifMasterTelephones = land.getMassifMasterTelephone();
            String landArea = land.getLandArea();
            Date creatTames = land.getCreateTime();
            String filePath = land.getLandManagement();
            String id = land.getId();
            axhkLandManagement.setId(id);
            axhkLandManagement.setMassifName(massifNames);
            axhkLandManagement.setMassifMasterName(massifMasterNames);
            axhkLandManagement.setMassifMasterTelephone(massifMasterTelephones);
            axhkLandManagement.setCreateTime((Date) creatTames);
            axhkLandManagement.setLandArea(landArea);
            try {
                if (filePath!=null) {
                    AxhkLandManagement axhkLandManagement1 = getLatitude(filePath);
                    bLatitudes = axhkLandManagement1.getBoundaryList();
                    oLatitudes = axhkLandManagement1.getObstacleList();
                    axhkLandManagement.setBoundaryList(bLatitudes);
                    axhkLandManagement.setObstacleList(oLatitudes);
                }
            }catch (Exception E){
                E.printStackTrace();
            }
            axhkLandManagements1.add(axhkLandManagement);
        }
        //对axhkLandManagement按时间进行排序
        Collections.sort(axhkLandManagements1, new Comparator<AxhkLandManagement>() {
            @Override
            public int compare(AxhkLandManagement o1, AxhkLandManagement o2) {
                // 升序
                //return o1.getCreateTime().compareTo(o2.getCreateTime());
                // 降序
                return o2.getCreateTime().compareTo(o1.getCreateTime());
            }
        });
        return axhkLandManagements1;
    }

    //  PC
    //读取文件获得三坐标 wjn
    //将坐标返给前端 地图展示使用
    @Override
    public AxhkLandManagement getLatitude(String filePath) throws Exception{
        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br= null;
        ArrayList<BLatitude> bLatitudes = new ArrayList<>();
        ArrayList<OLatitude> oLatitudes = new ArrayList<>();
        AxhkLandManagement axhkLandManagement = new AxhkLandManagement();
        //打开文件输入流
        fis = new FileInputStream(filePath);
        isr = new InputStreamReader(fis,"utf-8");
        //构造一个BufferedReader类来读取文件
        br = new BufferedReader(isr);
        //循环读出数据
        //使用readLine方法，一次读一行
        String latitudes = null;
        while(null != (latitudes=br.readLine())){
            BLatitude bLatitude = null;
            OLatitude oLatitude = null;
            String Blat = null;
            String Blng = null;
            String Olat = null;
            String Olng = null;
            //判断如果值不等于 空字符的话 添加
            if(!latitudes.equals("")){
                String[] latitudeAll = latitudes.split(",");
                for(int i=0;i<latitudeAll.length;i++){
                    //去除空格
                    String inner = latitudeAll[i].toString().trim();
                    //按 “=” 分割
                    String[] inners = inner.split("=");
                    if (i==0 && inners[0].equals("Blat")){
                        Blat = inners[1];
                    }else if(i==1 && inners[0].equals("Blng")){
                        Blng = inners[1];
                    }
                    if (i==0 && inners[0].equals("Olat")){
                        Olat = inners[1];
                    }else if(i==1 && inners[0].equals("Olng")){
                        Olng = inners[1];
                    }
                }
            }
            if(Blat != null && Blng != null){
                bLatitude = new BLatitude();
                Double lat = Double.parseDouble(Blat);
                bLatitude.setLat(lat);
                Double lng = Double.parseDouble(Blng);
                bLatitude.setLng(lng);
            }
            if(null != Olat && null != Olng){
                oLatitude = new OLatitude();
                Double olat = Double.parseDouble(Olat);
                oLatitude.setLat(olat);
                Double olng = Double.parseDouble(Olng);
                oLatitude.setLng(olng);
            }
            if(null != bLatitude){
                bLatitudes.add(bLatitude);
            }
            if(null != oLatitude){
                oLatitudes.add(oLatitude);
            }
        }
        axhkLandManagement.setBoundaryList(bLatitudes);
        axhkLandManagement.setObstacleList(oLatitudes);
        if(null != br){
            fis.close();
            isr.close();
            br.close();
        }
        return axhkLandManagement;
    }

    //PC
    //通过 地块名称查询 文件路劲 用于点击获取坐标-wjn
    @Override
    public ArrayList<ArrayList> getByPathName(String massifname) {
        AxhkLandManagement axhkLandManagement = new AxhkLandManagement();
        ArrayList<ArrayList> lists = new ArrayList<>();
        ArrayList<BLatitude> bLatitudes = new ArrayList<>();
        ArrayList<OLatitude> oLatitudes = new ArrayList<>();
        String filePath = axhkLandManagementMapper.getLandPathName(massifname);
        if(null != filePath){
            try {
                axhkLandManagement =  getLatitude(filePath);
                bLatitudes = axhkLandManagement.getBoundaryList();
                oLatitudes = axhkLandManagement.getObstacleList();
                lists.add(bLatitudes);
                lists.add(oLatitudes);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            return lists;
        }
        return lists;
    }


    //APP添加地块任务管理-wjn
    @Override
    public int addWork(@RequestBody AxhkWorkManagement axhkWorkManagement) {
        int i = 0;
        if(!axhkWorkManagement.getCreateBy().equals("") || !axhkWorkManagement.getLandId().equals("")){
            String id = UuId.getUUID();
            axhkWorkManagement.setId(id);
            //通多地块id查询地块名称
            String landName = axhkLandManagementMapper.getLandManagements(axhkWorkManagement.getLandId());
            axhkWorkManagement.setLandName(landName);
            i = axhkWorkManagementMapper.insetWork(axhkWorkManagement);
        }else{
            i = 0;
        }
        return i;
    }


    //根据群id获取到 该群所有任务信息-地块信息  返回给手机APP
    @Override
    public ArrayList<List> getByWorkAndLand(String fluckId) {
        ArrayList<List> lists = new ArrayList<>();
        ArrayList<BLatitude> bLatitudes = null;
        ArrayList<OLatitude> oLatitudes = null;
        //地块名称
        List<AxhkWorkManagement> axhkWorkManagements = axhkWorkManagementMapper.getWorkAndLand(fluckId);
        for (AxhkWorkManagement WorkManagement : axhkWorkManagements) {
            String landId = WorkManagement.getLandId();
            if (null != landId) {
                AxhkLandManagement axhkLandManagement = axhkLandManagementMapper.getLandAndWork(landId);
                String filePath = axhkLandManagement.getLandManagement();
                try {
                    if (filePath != null) {
                        AxhkLandManagement axhkLandManagement1 = getLatitude(filePath);
                        bLatitudes = axhkLandManagement1.getBoundaryList();
                        oLatitudes = axhkLandManagement1.getObstacleList();
                        axhkLandManagement.setBoundaryList(bLatitudes);
                        axhkLandManagement.setObstacleList(oLatitudes);
                    }
                    WorkManagement.setAxhkLandManagement(axhkLandManagement);
                } catch (Exception E) {
                    E.printStackTrace();
                }
            }
        }
        //对axhkWorkManagements按时间进行排序
        Collections.sort(axhkWorkManagements, new Comparator<AxhkWorkManagement>() {
            @Override
            public int compare(AxhkWorkManagement o1, AxhkWorkManagement o2) {
                // 升序
                //return o1.getStartWork().compareTo(o2.getStartWork());
                // 降序
                return o2.getStartWork().compareTo(o1.getStartWork());
            }
        });
        lists.add(axhkWorkManagements);
        return lists;
    }

    //根据 地块id 删除地块信息 和 本地文件 -----手机app修改 地块信息
    @Override
    public String getByUpdateLandMang(@RequestBody AxhkLandManagement axhkLandManagement) {
        int i = 0;
        String ids = null;
        String id = axhkLandManagement.getId();
        List<AxhkWorkManagement> axhkWorkManagements = axhkWorkManagementMapper.getByAxhkWorks(id); //根据地块id查询到的任务
        i = DeleteLandMang(id); // 调用删除地块信息的 方法
        if(i != 0){
            ids = addLands(axhkLandManagement);
            if(null != ids){
                if(axhkWorkManagements.size()!=0){
                    for(int n=0;n<axhkWorkManagements.size();n++){
                        AxhkWorkManagement axhkWorkManagement = axhkWorkManagements.get(n);
                        axhkWorkManagementMapper.getByUpdateWork(axhkWorkManagement.getId(),ids);
                    }
                }
            }
        }
        return ids;
    }

    //根据地块 id 删除地块信息 以及 本地地块坐标文件
    @Override
    public int getByDeleteLandMang(String id) {
        int i = 0;
        // 查询地块的名称
        String LandName = axhkLandManagementMapper.getLandManagements(id);
        if(null != LandName){
            AxhkWorkManagement axhkWorkManagement = axhkWorkManagementMapper.getByAxhkWorkManagement(LandName); // 查看该地块名称的任务是否存在
            if(axhkWorkManagement == null){ //如果为空 说明不存在
                i = DeleteLandMang(id);
            }else{ // 否则存在
                i = -1;
            }
        }
        return i;
    }

    /*
     * 通过客户端传递的经纬度 计算现有 距离最近地块的位置
     * telephone 电话号码
     * endLat 位置 经度
     * endLng 位置 维度
     * */
    @Override
    public ArrayList<AxhkLandManagement> getByScope(String fluckId, double endLat, double endLng) {
        List<AxhkLandManagements> axhkLandManagements = axhkWorkManagementMapper.getByWorkId(fluckId); //通过群id查询到该群下的所有地块
        ArrayList<AxhkLandManagement> axhkLandManagements1 = new ArrayList<>();
        ArrayList<BLatitude> bLatitudes = null;
        ArrayList<OLatitude> oLatitudes = null;
        double km = 5000.00;
        Scope scope = new Scope(); // 创建方法对象 调用方法
        for(AxhkLandManagements land : axhkLandManagements){
            String id = land.getId();
            String filePath = land.getLandManagement(); // 遍历出每个 地块的经纬度 文件储存路劲
            try {
                ArrayList<BLatitude> bLatitudes1 = scope.getLatitude(filePath); //返回 一个经纬度集合
                if(null != bLatitudes1){ //当遍历后的经纬度集合不为 null的 时候调用方法计算中心点经纬度
                    BLatitude bLatitude = scope.getCenterOfGravityPoint(bLatitudes1);
                    double start_latitude = bLatitude.getLat(); //每个经纬度 对象 获取中心点的经度
                    double start_longitude = bLatitude.getLng(); //每个经纬度 对象 获取中心点的维度
                    double distance = scope.getDistance(start_latitude,start_longitude,endLat,endLng);
                    if(distance <= km){ //进行比较 小于 5公里的
                        AxhkLandManagements axhkLandManagements2 = axhkLandManagementMapper.getAxhkLandManagements(id);
                        AxhkLandManagement axhkLandManagement = new AxhkLandManagement();
                        String massifNames = axhkLandManagements2.getMassifName();
                        String massifMasterNames = axhkLandManagements2.getMassifMasterName();
                        String massifMasterTelephones = axhkLandManagements2.getMassifMasterTelephone();
                        String landArea = axhkLandManagements2.getLandArea();
                        Date creatTames = axhkLandManagements2.getCreateTime();
                        String filePaths = axhkLandManagements2.getLandManagement();
                        axhkLandManagement.setId(id);
                        axhkLandManagement.setMassifName(massifNames);
                        axhkLandManagement.setMassifMasterName(massifMasterNames);
                        axhkLandManagement.setMassifMasterTelephone(massifMasterTelephones);
                        axhkLandManagement.setCreateTime((Date) creatTames);
                        axhkLandManagement.setLandArea(landArea);
                        try {
                            if (filePath != null) {
                                AxhkLandManagement axhkLandManagement1 = getLatitude(filePaths);
                                bLatitudes = axhkLandManagement1.getBoundaryList();
                                oLatitudes = axhkLandManagement1.getObstacleList();
                                axhkLandManagement.setBoundaryList(bLatitudes);
                                axhkLandManagement.setObstacleList(oLatitudes);
                            }
                        } catch (Exception E) {
                            E.printStackTrace();
                        }
                        if(null != axhkLandManagement) {
                            axhkLandManagements1.add(axhkLandManagement);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if(null != axhkLandManagements1) {
            //对axhkLandManagement按时间进行排序
            Collections.sort(axhkLandManagements1, new Comparator<AxhkLandManagement>() {
                @Override
                public int compare(AxhkLandManagement o1, AxhkLandManagement o2) {
                    // 升序
                    //return o1.getCreateTime().compareTo(o2.getCreateTime());
                    // 降序
                    return o2.getCreateTime().compareTo(o1.getCreateTime());
                }
            });
        }
        return axhkLandManagements1;
    }

    /*
     *修改 任务完成的 标识
     * String workId 任务id
     * String createBy 用户名 修改人
     * */
    @Override
    public String getUpdateFinih(String createBy,String workId) {
        if(null != workId){
            int finih = 1;
            int i = axhkWorkManagementMapper.getUpdateFinish(createBy,workId,finih);
            if(i>0){
                return "修改成功!";
            }else{
                return "A";
            }
        }else{
            return "B";
        }
    }

    /*
     * 查看该用户下所有任务的完成信息
     * String createBy 完成人名字
     * int finish
     * */
    @Override
    public WorkFinish AllFinishWork(String createBy,String fluckId) {
        WorkFinish workFinish = new WorkFinish();
        int finish = 1;
        List<AxhkWorkManagement> axhkWorkManagements = null;
        ArrayList<BLatitude> bLatitudes = null;
        ArrayList<OLatitude> oLatitudes = null;
        int SumSortie = 0; //总架次
        Double SumArea = 0.0; //总面积
        String SumTime = null; //总时长
        if(null != createBy && fluckId.equals("否")){
            axhkWorkManagements = axhkWorkManagementMapper.getCreateByFinishWork(createBy,finish);
        }else{
            axhkWorkManagements = axhkWorkManagementMapper.getFluckIdFinishFluck(fluckId,finish);
        }
        for(AxhkWorkManagement WorkManagement : axhkWorkManagements){
            String landId = WorkManagement.getLandId();
            if (null != landId) {
                AxhkLandManagement axhkLandManagement = axhkLandManagementMapper.getLandAndWork(landId);
                String filePath = axhkLandManagement.getLandManagement();
                String land_area = axhkLandManagement.getLandArea();
                if(null != land_area){
                    SumArea = Double.valueOf(land_area)+SumArea;
                }
                try {
                    if (filePath != null) {
                        AxhkLandManagement axhkLandManagement1 = getLatitude(filePath);
                        bLatitudes = axhkLandManagement1.getBoundaryList();
                        oLatitudes = axhkLandManagement1.getObstacleList();
                        axhkLandManagement.setBoundaryList(bLatitudes);
                        axhkLandManagement.setObstacleList(oLatitudes);
                    }
                    WorkManagement.setAxhkLandManagement(axhkLandManagement);
                } catch (Exception E) {
                    E.printStackTrace();
                }
            }
        }
        workFinish.setSumArea(SumArea);
        workFinish.setSumSortie(SumSortie);
        workFinish.setSumTime(SumTime);
        workFinish.setAxhkWorkManagement(axhkWorkManagements);
        return workFinish;
    }

    /*
     * 根据地块 id 删除地块信息 以及 本地地块坐标文件
     * 共同调用类
     * */
    public int DeleteLandMang(String id) {
        int i = 0;
        String filePath = axhkLandManagementMapper.getByPathName(id); //获取文件名称
        if(null != filePath) {
            DeleteFile deleteF = new DeleteFile();
            int s = deleteF.deleteFile(filePath);
            if(s == 1){ //当文件被删除后 a=1
                i = axhkLandManagementMapper.deleteLandMang(id);
            }
        }
        return i;
    }



}
